import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { updateTodo, editTodo, editTodoName } from '../../redux/slice'
import './Item.css'
export default function Item(props) {
  const [tN, settN] = useState('')
  const editId = useSelector((state) => state.todoList.editId)
  const dispatch = useDispatch()
  const {
    todo: { id, todoName, isDone },
  } = props
  return (
    <li>
      {editId !== id ? (
        <label>
          <input
            type="checkbox"
            checked={isDone}
            onChange={() => {
              dispatch(updateTodo(id))
            }}
          />
          <span className={isDone ? 'done' : ''}>{todoName}</span>
        </label>
      ) : (
        <input
          type="text"
          value={tN}
          onChange={(e) => {
            settN(e.target.value.trim())
          }}
          onKeyDown={(e) => {
            if (!tN || e.key !== 'Enter') return
            dispatch(editTodoName({ id, todoName: tN }))
            dispatch(editTodo(undefined))
          }}
        />
      )}
      <button className="btn btn-danger">删除</button>
      <button
        className="btn btn-danger"
        style={{ border: 'none', backgroundColor: 'skyblue', marginRight: 10 }}
        onClick={() => {
          dispatch(editTodo(editId !== id ? id : undefined))
          settN(todoName)
        }}
      >
        {editId !== id ? '编辑' : '取消'}
      </button>
    </li>
  )
}
